import { HttpException, Injectable } from '@nestjs/common';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Role } from '../role/entities/role.entity';
import { Repository } from 'typeorm';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
    @InjectRepository(Role) private readonly role: Repository<Role>, // private readonly roleService: RoleService,
  ) {}

  async create(createUserDto) {
    console.log('createUserDto: ', createUserDto);
    const { userName, passWord, type = 3 } = createUserDto;
    console.log('type: ', type);
    if (!userName || !passWord) {
      throw new HttpException('缺少参数', 400);
    }
    const userDoc = await this.user.findOne({ where: { userName } });
    if (userDoc) {
      throw new HttpException('用户名已存在', 400);
    }

    const roleDoc = await this.role.findOne({ where: { type } });
    console.log('roleDoc: ', roleDoc);

    await this.user.save({
      ...createUserDto,
      role: roleDoc,
      avatar:
        'http://127.0.0.1:4000/src/assets/d763a4ca85e149f4940d8f8603784ae3.jpeg',
    });
    return null;
  }

  async findAll(req: any) {
    console.log('req: ', req);
    const { page = 1, pageSize = 5, type, userName } = req;
    console.log('type: ', type);
    const users = await this.user
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.role', 'role')
      .orderBy('user.role', 'DESC');
    if (type) {
      await users.where('role.type = :type', { type });
    }
    if (userName) {
      await users.where('user.userName = :userName', { userName });
    }
    await users.limit(pageSize);
    await users.offset((page - 1) * pageSize);
    const total = await users.getCount();
    const list = await users.getMany();
    const renderList = list.map((user) => {
      const { role, ...props } = user;
      return {
        ...props,
        type: role?.type,
      };
    });

    return { list: renderList, total };
  }

  async login(res) {
    const { userName, passWord } = res;
    if (!userName || !passWord) {
      throw new HttpException('缺少参数', 400);
    }
    const user = await this.user.findOne({
      where: { userName, passWord },
      relations: { role: true },
    });
    if (!user) {
      throw new HttpException('账号或密码输入错误', 400);
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { role, passWord: pwd, ...rest } = user;
    console.log('user: ', user);
    return {
      data: {
        ...rest,
        auth: role?.func,
        role: role?.type,
      },
      token: 'block-admin',
    };
  }

  async update(updateUserDto) {
    const { userId, type, ...res } = updateUserDto;
    const exist = await this.user
      .createQueryBuilder('user')
      .select('user')
      .where('user.userId = :userId', { userId })
      .getOne();
    if (!exist) {
      throw new HttpException(`id为${userId}的用户不存在`, 400);
    }
    const user = this.user.merge(res, updateUserDto);
    const roleDoc = await this.role.findOne({ where: { type } });
    console.log('roleDoc: ', roleDoc);
    console.log('user: ', user);
    await this.user.save({
      ...user,
      role: roleDoc,
    });
    return null;
  }

  async remove(data) {
    const { userId } = data;
    const exist = await this.user.findOneBy(data);
    console.log('exist: ', exist);
    if (!exist) {
      throw new HttpException(`id为${userId}的电影不存在`, 400);
    }
    await this.user.remove(exist);
    return userId;
  }
}
